package com.cc.cbdb.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AbsListView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.cc.cbdb.R;
import com.cc.cbdb.adapter.SelectedDataListAdapter;
import com.cc.cbdb.common.constants.Constant;
import com.cc.cbdb.common.utils.NetRequest;
import com.cc.cbdb.common.utils.SPUtil;
import com.cc.cbdb.common.utils.StringUtil;
import com.cc.cbdb.common.utils.ToastUtil;
import com.cc.cbdb.entity.EthnicityTribeCodes;
import com.cc.cbdb.entity.KinshipCodes;
import com.cc.cbdb.entity.PageBean;
import com.cc.cbdb.entity.QBiogCustom;
import com.cc.cbdb.entity.QInstitutionCustom;
import com.cc.cbdb.entity.SelectedCustom;
import com.cc.cbdb.entity.StatusCodes;
import com.cc.cbdb.view.LoadingDialog;
import com.cc.cbdb.view.searchView.ICallBack;
import com.cc.cbdb.view.searchView.SearchView;
import com.cc.cbdb.view.searchView.bCallBack;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.lang.ref.WeakReference;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import okhttp3.Request;

public class SelectedActivity extends AppCompatActivity implements View.OnClickListener{

    private static final String TAG = "SelectedActivity";

    private Context mContext;
    private List<SelectedCustom> mResults = new ArrayList<>();
    private HashMap<Integer,Boolean> mCheckStatus = new HashMap<>();
    private int mSelectCount;
    private ListView lv_content;
    private TextView tv_page_info,tv_search_count,select_count;
    private SelectedDataListAdapter mAdapter;
    private LoadingDialog mLoadingDialog;
    private boolean isLoad = false;
    //当前页码
    private int mPageNum = 1;
    //总页码
    private int mTotalPage;
    //搜索内容
    private String mSearchStr = "";
    private boolean scrollFlag = false; // 标记是否滑动
    private static final int DEFAUT = 0;
    private static final int NEXT_PAGE = 1;  //下一页
    private static final int PRE_PAGE = 2;   //上一页
    private static final int VISIBLE = View.VISIBLE;
    private static final int INVISIBLE = View.INVISIBLE;
    //其他页面传递过来的请求参数
    private String mTitle="";
    private int PAGECODE;

    private MsgHandler handler;

    private static class MsgHandler extends Handler{
        private WeakReference<SelectedActivity> reference;

        MsgHandler(SelectedActivity activity){
            reference = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            SelectedActivity activity = reference.get();
            Bundle data = msg.getData();
            if (activity.mAdapter == null) {
                activity.buildAdapter();
                activity.lv_content.setAdapter(activity.mAdapter);
            } else {
                activity.mAdapter.notifyDataSetChanged();
                switch (msg.what) {
                    case NEXT_PAGE:
                        //上滑（下一页），条目更新后跳到第一个
                        if (!activity.lv_content.isStackFromBottom()) {
                            activity.lv_content.setStackFromBottom(true);
                        }
                        activity.lv_content.setStackFromBottom(false);
                        break;
                    case PRE_PAGE:
                        //下滑（上一页），条目更新后跳到最后一个
                        if (!activity.lv_content.isStackFromBottom()) {
                            activity.lv_content.setStackFromBottom(false);
                        }
                        activity.lv_content.setStackFromBottom(true);
                        break;
                    case DEFAUT:
                        break;
                }
            }
            activity.mLoadingDialog.dismiss();
            activity.tv_page_info.setText("当前页：" + data.getInt("pageNum") + " 总页数：" + data.getInt("totalPage"));
            activity.tv_search_count.setText("查询到" + data.getInt("totalCount") + "条数据");
            if (activity.tv_page_info.getVisibility() == INVISIBLE || activity.tv_search_count.getVisibility() == INVISIBLE) {
                activity.tv_page_info.setVisibility(VISIBLE);
                activity.tv_search_count.setVisibility(VISIBLE);
            }
            activity.isLoad = false;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_selected);
        mContext = this;
        initUI();
        initData();
    }

    private void initUI() {
        handler = new MsgHandler(this);
        //获取配置页面参数
        Intent intent = getIntent();
        mTitle = intent.getStringExtra("title");
        String tabName = intent.getStringExtra("tabName");

        LoadingDialog.Builder builder = new LoadingDialog.Builder(mContext);
        builder.setMessage("加载中...");
        mLoadingDialog = builder.create();

        //绑定组件
        TextView titleBar = findViewById(R.id.titleBar);
        SearchView searchView = findViewById(R.id.search_view);
        searchView.setTabName(tabName);
        searchView.queryData("");
        lv_content = findViewById(R.id.lv_content);
        tv_page_info = findViewById(R.id.tv_page_info);
        tv_search_count = findViewById(R.id.tv_search_count);

        select_count = findViewById(R.id.select_count);
        TextView tv_confirm = findViewById(R.id.tv_confirm);
        LinearLayout ll_select = findViewById(R.id.ll_select);
        LinearLayout ll_disSelect = findViewById(R.id.ll_disSelect);

        ll_select.setOnClickListener(this);
        ll_disSelect.setOnClickListener(this);
        tv_confirm.setOnClickListener(this);

        titleBar.setText(mTitle);

        // 设置点击搜索按键后的操作（通过回调接口）
        // 参数 = 搜索框输入的内容
        searchView.setOnClickSearch(new ICallBack() {
            @Override
            public void SearchAciton(String string) {
//            Log.d(TAG,"搜索的内容为：" + string);

            mSearchStr = string;
            //请求后台接口
            getDataAsync(DEFAUT);
            }
        });

        // 设置点击返回按键后的操作（通过回调接口）
        searchView.setOnClickBack(new bCallBack() {
            @Override
            public void BackAciton() {
                finish();
            }
        });

        // 给listview添加滚动监听
        lv_content.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView absListView, int scrollState) {
                if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL) {
                    scrollFlag = true;
                } else {
                    scrollFlag = false;
                }

                if (mResults != null) {
                    if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE
                            && lv_content.getLastVisiblePosition() >= mResults.size() - 1
                            && !isLoad && !scrollFlag) {

                        isLoad = true;

                        //加载下一页数据
                        if (mPageNum < mTotalPage) {
                            mPageNum++;
                            getDataAsync(NEXT_PAGE);
                        }else {
                            ToastUtil.showShort(mContext,"已经到底了~");
                            isLoad = false;
                        }
                    }
                    // 判断滚动到顶部
                    if (lv_content.getChildCount() > 0 && lv_content.getFirstVisiblePosition() == 0
                            && lv_content.getChildAt(0).getTop() >= 0
                            && !isLoad && !scrollFlag) {
                        isLoad = true;
                        //加载上一页数据
                        if (mPageNum > 1) {
                            mPageNum--;
                            getDataAsync(PRE_PAGE);
                        } else {
                            ToastUtil.showShort(mContext, "已经到顶了~");
                            isLoad = false;
                        }
                    }
                }
            }

            @Override
            public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

            }
        });
    }

    private void initData(){
        getSPData();
        getDataAsync(DEFAUT);
    }

    /**
     * 设置adapter及其中item的点击事件
     */
    private void buildAdapter() {
        if (PAGECODE == 10){
            mAdapter = new SelectedDataListAdapter(this,1,mResults,mCheckStatus);
        }else {
            mAdapter = new SelectedDataListAdapter(this,0,mResults,mCheckStatus);
        }

        mAdapter.setListener(new SelectedDataListAdapter.CheckedListener() {
            @Override
            public void statisticChecked(boolean isChecked) {
                if (isChecked){
                    mSelectCount++;
                }else {
                    mSelectCount--;
                }
                if (mSelectCount > 0) {
                    select_count.setText("("+mSelectCount+")");
                }else {
                    select_count.setText("");
                }
            }
        });
    }

    /**
     * 异步请求接口
     * @param mode  翻页模式
     */
    private void getDataAsync(final int mode){
        mLoadingDialog.show();

        String url = Constant.DOMAIN_PROJECT;
        HashMap<String,String> params = new HashMap<>();
        //根据title来判断请求的接口，设置不同的请求参数
        switch (mTitle){
            case Constant.TITLE.TITLE_QETHNICITY:
                url += Constant.URL.URL_QETHNICITY;
                PAGECODE = 1;
                break;
            case Constant.TITLE.TITLE_QINSTITUTION:
                url += Constant.URL.URL_QINSTITUTION;
                PAGECODE = 5;
                break;
            case Constant.TITLE.TITLE_QSTATUSCODE:
                url += Constant.URL.URL_QSTATUSCODE;
                PAGECODE = 6;
                break;
            case Constant.TITLE.TITLE_KINSHIP:
                url += Constant.URL.URL_QKINSHIP;
                PAGECODE = 7;
                break;
            case Constant.TITLE.TITLE_SELECTPERSON:
                url += Constant.URL.URL_QNAME;
                PAGECODE = 10;
                break;
        }
        if (!mSearchStr.equals("") && mPageNum != 1) {
            params.put("pageNum","1");
        }else {
            params.put("pageNum",mPageNum+"");
        }
        params.put("name",mSearchStr);

        Log.d(TAG, "params: "+params);

        NetRequest.getFormRequest(url, params, new NetRequest.DataCallBack() {
            @Override
            public void requestSuccess(String result) throws Exception {
                Log.d(TAG,"json返回数据："+result);

                mResults.clear();
                PageBean pageBean = null;
                switch (PAGECODE){
                    case 1:
                        pageBean = new Gson().fromJson(result, new TypeToken<PageBean<EthnicityTribeCodes>>(){}.getType());
                        List<EthnicityTribeCodes> list1 = (List<EthnicityTribeCodes>) pageBean.getRecordList();
                        for (EthnicityTribeCodes e: list1) {
                            mResults.add(new SelectedCustom(e.getcEthnicityCode(),e.getcNameChn(),e.getcNotes()));
                            if (mCheckStatus.get(e.getcEthnicityCode()) == null) {
                                mCheckStatus.put(e.getcEthnicityCode(),false);
                            }
                        }
                        break;
                    case 5:
                        pageBean = new Gson().fromJson(result, new TypeToken<PageBean<QInstitutionCustom>>(){}.getType());
                        List<QInstitutionCustom> list2 = (List<QInstitutionCustom>) pageBean.getRecordList();
                        for (QInstitutionCustom e: list2) {
                            mResults.add(new SelectedCustom(e.getInstCode(),e.getInstName(),jointAddrName(e)));
                            if (mCheckStatus.get(e.getInstCode()) == null) {
                                mCheckStatus.put(e.getInstCode(),false);
                            }
                        }
                        break;
                    case 6:
                        pageBean = new Gson().fromJson(result, new TypeToken<PageBean<StatusCodes>>(){}.getType());
                        List<StatusCodes> list3 = (List<StatusCodes>) pageBean.getRecordList();
                        for (StatusCodes e: list3) {
                            mResults.add(new SelectedCustom(e.getcStatusCode(),e.getcStatusDescChn(),""));
                            if (mCheckStatus.get(e.getcStatusCode()) == null) {
                                mCheckStatus.put(e.getcStatusCode(),false);
                            }
                        }
                        break;
                    case 7:
                        pageBean = new Gson().fromJson(result, new TypeToken<PageBean<KinshipCodes>>(){}.getType());
                        List<KinshipCodes> list4 = (List<KinshipCodes>) pageBean.getRecordList();
                        for (KinshipCodes e: list4) {
                            mResults.add(new SelectedCustom(e.getcKincode(),e.getcKinrelChn(),""));
                            if (mCheckStatus.get(e.getcKincode()) == null) {
                                mCheckStatus.put(e.getcKincode(),false);
                            }
                        }
                        break;
                    case 10:
                        pageBean = new Gson().fromJson(result, new TypeToken<PageBean<QBiogCustom>>(){}.getType());
                        List<QBiogCustom> list5 = (List<QBiogCustom>) pageBean.getRecordList();
                        for (QBiogCustom e: list5) {
                            mResults.add(new SelectedCustom(e.getPersonId(),e.getName(),e.getNameChn(),e.getDyChn(),e.getAltName()));
                            if (mCheckStatus.get(e.getPersonId()) == null) {
                                mCheckStatus.put(e.getPersonId(),false);
                            }
                        }
                        break;
                }

                mTotalPage = pageBean.getTotalPage();

                Message message = Message.obtain();
                message.what= mode;
                Bundle bundle = new Bundle();
                bundle.putInt("pageNum", mPageNum);
                bundle.putInt("totalPage", pageBean.getTotalPage());
                bundle.putInt("totalCount", pageBean.getTotalCount());
                message.setData(bundle);
                handler.sendMessage(message);
            }

            @Override
            public void requestFailure(Request request, IOException e) {
                mLoadingDialog.dismiss();
                ToastUtil.showShort(mContext,"请求错误！");
            }
        });
    }

    //处理地名
    private String jointAddrName(QInstitutionCustom e) {
        String addrName = e.getAddrName();
        String[] array = new String[5];
        StringBuilder sb = new StringBuilder();
        if (StringUtil.isNotNull(addrName)) {
            for (int i = 0; i < array.length; i++) {
                try {
                    Method method = Class.forName("com.cc.cbdb.entity.QInstitutionCustom")
                            .getMethod("getBelongs"+(i+1)+"Name");
                    array[i] = (String) method.invoke(e);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
            for (int i = array.length-1; i > 0 ; i--) {
                if (array[i] != null) {
                    sb.append(array[i]);
                    sb.append("-");
                }
            }
            if (StringUtil.isNotNull(sb.toString())){
                return sb.append(addrName).toString();
            }
        }
        return "";
    }

    private void getSPData(){
        String checkedStr = (String) SPUtil.get(mContext,mTitle,"");
        if (!checkedStr.equals("")){
            String[] split = checkedStr.split(",");
            mSelectCount = split.length;
            for (int i = 0; i < split.length; i++) {
                mCheckStatus.put(Integer.parseInt(split[i]),true);
            }
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.ll_select:
                // 刷新listview的checkbox状态
                mAdapter.checkAll();
                int count1 = 0;
                Iterator<Map.Entry<Integer, Boolean>> iterator1 = mCheckStatus.entrySet().iterator();
                while (iterator1.hasNext()){
                    if (iterator1.next().getValue()) {
                        count1++;
                    }
                }
                mSelectCount = count1;
                select_count.setText("("+mSelectCount+")");
                break;
            case R.id.ll_disSelect:
                mAdapter.disCheckAll();
                int count2 = 0;
                Iterator<Map.Entry<Integer, Boolean>> iterator2 = mCheckStatus.entrySet().iterator();
                while (iterator2.hasNext()){
                    if (iterator2.next().getValue()) {
                        count2++;
                    }
                }
                mSelectCount = count2;
                select_count.setText("("+mSelectCount+")");
                break;
            case R.id.tv_confirm:
                StringBuilder sb = new StringBuilder();
                Iterator<Map.Entry<Integer, Boolean>> iterator3 = mCheckStatus.entrySet().iterator();
                while (iterator3.hasNext()){
                    Map.Entry<Integer, Boolean> entry = iterator3.next();
                    if (entry.getValue()) {
                        sb.append(entry.getKey());
                        sb.append(",");
                    }
                }
                String selectId = sb.toString();
                SPUtil.put(mContext,mTitle,selectId);
                Intent intent = new Intent();
                intent.putExtra("checkedIds",selectId);
                setResult(PAGECODE,intent);
                finish();
                break;
        }

    }
}
